const jql = require('jql')
const result = require('result')

module.exports = {
  _before() {
    //在this中存入db对象
    this.db = jql(this, 'order')
  },
  //获取订单列表
  async getOrderList(userId) {
    //获取商品表和订单商品表数据库对象
    const orderCommoditiesDb = jql(this, 'order-commodities')
    const commoditiesDb = jql(this, 'commodity')
    const addressDb = jql(this, 'address')

    //获取订单数据
    const orderTemp = this.db.where(`user_id == "${userId}"`).getTemp()
    const addressTemp = addressDb.getTemp()
    const orders = (await jql(this, orderTemp, addressTemp).get()).data

    //数据请求合集
    const multis = []
    //遍历查询
    for (const {_id} of orders) {
      //查询在订单农品表中订单相同的数据
      const orderCommoditiesTemp = orderCommoditiesDb.where(`order_id == "${_id}"`).getTemp()
      const commoditiesTemp = commoditiesDb.getTemp()

      //将联表查询的请求推送到请求合集中
      multis.push(jql(this, orderCommoditiesTemp, commoditiesTemp).getTemp())
    }

    //统一发送请求获取订单农品
    const db = uniCloud.databaseForJQL({clientInfo: this.getClientInfo()})
    const orderCommodities = (await db.multiSend(...multis)).dataList

    //返回联表查询结果
    return orders.map((item, index) => ({
      ...item,
      order_commodities: orderCommodities[index].data
    }))
  }
}
